package com.wiscamp.ninechapters.threeparties.wechat;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.wiscamp.ninechapters.common.core.JsonHelper;
import com.wiscamp.ninechapters.common.exception.ExceptionHandler;
import com.wiscamp.ninechapters.threeparties.wechat.config.WxMaConfiguration;
import cube.ddd.aspect.HandleServiceException;
import jakarta.validation.constraints.NotBlank;
import me.chanjar.weixin.common.error.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * Wechat Service
 */
@Service
public class WechatService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

/*    @Autowired
    private AuditLogService logService;*/

    /**
     * wechat login
     *
     * @param appId
     * @param code
     * @return
     */

    @HandleServiceException
    public String login(@NotBlank String appId, @NotBlank String code) {
        final WxMaService wxService = WxMaConfiguration.getMaService(appId);
        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            return JsonHelper.toJson(session);
        } catch (WxErrorException e) {
            ExceptionHandler.throwServiceException(e, logger, "UNKNOWN",
                    appId + ":" + code);
        }
        return "";
    }
}
